package com.woniuxy.purchasemanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.woniuxy.commons.entity.purchaseManager.PurchaseOrderEntity;
import com.woniuxy.commons.entity.purchaseManager.base.PageResult;
import com.woniuxy.commons.entity.purchaseManager.base.QueryPageBean;
import com.woniuxy.commons.entity.purchaseManager.dto.PurchaseOrderGoodsEditDTO;
import com.woniuxy.commons.rabbit.GoldService;
import com.woniuxy.commons.rabbit.RabbitMqConst;
import com.woniuxy.commons.utils.PageUtils;
import com.woniuxy.commons.utils.Query;
import com.woniuxy.purchasemanager.dao.PurchaseOrderDao;
import com.woniuxy.purchasemanager.service.PurchaseOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("purchaseOrderService")
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderDao, PurchaseOrderEntity> implements PurchaseOrderService {

    public static final Logger LOGGER = LoggerFactory.getLogger(PurchaseOrderServiceImpl.class);

    @Resource
    private PurchaseOrderDao purchaseOrderDao;

    //注入rabbitmq服务
    @Resource
    private GoldService goldService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseOrderEntity> page = this.page(
                new Query<PurchaseOrderEntity>().getPage(params),
                new QueryWrapper<PurchaseOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageResult<PurchaseOrderEntity> findPage(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();

        Integer pageSize = queryPageBean.getPageSize();
        //查询条件
        String queryString = queryPageBean.getQueryString();
        //开始时间
        Date startDate = queryPageBean.getStartDate();
        //结束时间
        Date endDate = queryPageBean.getEndDate();
        //分页查询
        PageMethod.startPage(currentPage, pageSize);

        Page<PurchaseOrderEntity> page = purchaseOrderDao.findPageByCondition(queryString, startDate, endDate);

        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public PurchaseOrderGoodsEditDTO getPurchaseOrderGoodsEditData(Integer purchaseOrderId) {

        return purchaseOrderDao.getPurchaseOrderGoodsEditData(purchaseOrderId);
    }

    @Transactional
    @Override
    public boolean deleteIntermediateTable(Integer purchaseOrderId, List splitGoodsIds) {

        //删除联系
        boolean b = purchaseOrderDao.deleteIntermediateTable(purchaseOrderId, splitGoodsIds);
        if (!b) {
            LOGGER.error("拆单失败，删除中间表错误！");
            return false;
        }
        return true;
    }

    @Transactional
    @Override
    public boolean split(Map<String, Object> map) {
        Integer purchaseOrderId = (Integer) map.get("purchaseOrderId");
        List splitGoodsIds = (List) (map.get("purchaseOrderGoodsIds"));
        if (purchaseOrderId == null || splitGoodsIds == null) {
            return false;
        }
        PurchaseOrderEntity purchaseOrderEntity = purchaseOrderDao.selectById(purchaseOrderId);
        Assert.notNull(purchaseOrderEntity, "查询purchaseOrderEntity数据为null!");
        //获取原先的采购单id
        Integer purchaseOrderId2 = purchaseOrderEntity.getPurchaseOrderId();
        //查出当前采购单的id对应的商品数量=1，并且splitGoodsIds的数量也是=1，那么就将原来的采购单状态修改为已取消状态
        Integer num = purchaseOrderDao.selectPurchaseOrderGoodsCount(purchaseOrderId);
        if (num == 1 && splitGoodsIds.size() == 1) {
            purchaseOrderDao.setCancelStatus(purchaseOrderId);
        }
        //删除不在传入的商品id集合的中间表
        purchaseOrderDao.deleteIntermediateTable(purchaseOrderId2, splitGoodsIds);
        //新建采购单
        PurchaseOrderEntity purchaseOrderEntity1 = new PurchaseOrderEntity();
        //忽略属性
        BeanUtils.copyProperties(purchaseOrderEntity, purchaseOrderEntity1, "purchaseOrderId");
        //插入采购单表，返回
        purchaseOrderDao.insertPurchaseOrder(purchaseOrderEntity1);
        Integer purchaseOrderId1 = purchaseOrderEntity1.getPurchaseOrderId();
        //重新插入中间表重新定义关系
        boolean b = purchaseOrderDao.insertNewMiddleTable(purchaseOrderId1, splitGoodsIds);
        if (!b) {
            LOGGER.error("拆单失败，插入中间表错误！");
            return false;
        }
        return true;
    }

    /**
     * 审核 将采购单状态修改为已完成
     *
     * @param purchaseOrderId:
     * @Author: xianhao
     * @Date: 2022/4/27 19:19
     * @return: int
     **/
    @Transactional
    @Override
    public boolean xMan(Integer purchaseOrderId) {
        int num = purchaseOrderDao.update(null, new UpdateWrapper<PurchaseOrderEntity>()
                .eq("purchase_order_id", purchaseOrderId)
                .set("purchase_order_status", 3));
        if (num == 0) {
            //更新失败
            LOGGER.error("采购单审核失败");
            return false;
        }
        //使用rabbitmq将采购单id发送给仓库服务
        goldService.send(purchaseOrderId+"","", RabbitMqConst.PURCHASE_ORDER_ROUTING_OK_KEY);
        return true;
    }

    /**
     * 反审，将状态修改为编辑状态，需要再次提交，调用仓库服务添加采购入库状态
     *
     * @param purchaseOrderId:
     * @Author: xianhao
     * @Date: 2022/4/27 20:23
     * @return: int
     **/
    @Transactional
    @Override
    public boolean unxMan(Integer purchaseOrderId) {
        int num = purchaseOrderDao.update(null, new UpdateWrapper<PurchaseOrderEntity>()
                .eq("purchase_order_id", purchaseOrderId)
                .set("purchase_order_status", 1));
        if (num == 0) {
            //反审失败
            LOGGER.error("采购单反审核失败");
            return false;
        }
        //使用rabbitmq将反审的采购单id发送给仓库服务,仓库直接将状态改为取消
        goldService.send(purchaseOrderId+"","", RabbitMqConst.PURCHASE_ORDER_ROUTING_CANCEL_KEY);
        return true;
    }
}